import { defineStore } from "pinia";

const useTagsViewStore = defineStore(
    'tags-view',
    {
        state: () => ({
            visitedViews: [],
            cachedViews: []
        }),
        actions: {
            addVisitedView(view) {
                // 检查是否已经存在该视图
                if (this.visitedViews.some(v => v.path === view.path)) return;

                // 添加到已访问视图列表
                this.visitedViews.push({
                    ...view,
                    title: view.meta?.title || '默认标题'
                });

                // 添加到缓存视图列表
                if (!this.cachedViews.includes(view.name)) {
                    this.cachedViews.push(view.name);
                }
            },
            delVisitedView(view) {
                // 从已访问视图列表中删除
                const index = this.visitedViews.findIndex(v => v.path === view.path);
                if (index > -1) {
                    this.visitedViews.splice(index, 1);
                }

                // 从缓存视图列表中删除
                const cacheIndex = this.cachedViews.indexOf(view.name);
                if (cacheIndex > -1) {
                    this.cachedViews.splice(cacheIndex, 1);
                }
            },
            delOthersVisitedViews(view) {
                // 保留当前视图，删除其他所有视图
                this.visitedViews = this.visitedViews.filter(v => v.path === view.path);
                this.cachedViews = [view.name];
            },
            delAllVisitedViews() {
                // 删除所有已访问视图
                this.visitedViews = [];
                this.cachedViews = [];
            },
            updateVisitedView(view) {
                // 更新已访问视图的信息
                for (const v of this.visitedViews) {
                    if (v.path === view.path) {
                        v.title = view.meta?.title || '默认标题';
                        break;
                    }
                }
            }
        }
    }
)

export default useTagsViewStore;